//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  onLoad: function () {
    var that = this;
    //以下为小程序默认函数
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return;
    }
    //加载初始数据
    app.getOpenid().then(function (res) {
      console.log("in promise function: " + app.globalData.openid);

      wx.request({
        url: 'https://toastmasters.istudy.club/users?openid=' + app.globalData.openid,
        header: {
          "Content-Type": "application/xml"
        },
        success: function (res) {
          console.log("status of fetching user data: " + res.statusCode)
          console.log(JSON.stringify(res.data))
          //convert user data received in res to array type
          var user = []
          if (res.data instanceof Array) {
            console.log("got an user array:"+res.data)
            user = res.data
            console.log(user)
          } else {
            user.push(res.data)
          }

          console.log("number of users: " + user.length)
          if (res.statusCode == 200 && user.length == 0) {

            //detected user doesn't exist, create and post user
              wx.request({
                url: 'https://toastmasters.istudy.club/users',
                method: 'POST',
                data: {
                  name: 'Gavin',
                  openid: app.globalData.openid,
                },
                header: {
                  "Content-Type": "application/xml"
                },
                success: function (res) {
                  console.log("posted user" + JSON.stringify(res.data))
                },
                fail: function (error) {
                  console.log(error)
                },
            })
          } else if (res.statusCode == 200 && user.length == 1) {
            // console.log("ttt:"+JSON.stringify(user))
            if (!app.globalData.uid) {
              app.globalData.uid = user[0].id
              console.log("user id set: " + app.globalData.uid)
            }
            that.setData({
              habits: user[0].habits
            })
            console.log("user already exists, habbits data loaded successfully");
          } else if (res.statusCode == 200 && user.length > 1) {
            console.log("duplicate records of the same user, please check database");
          } 
        },
        fail: function (error) {
          console.log(error)
        }
      })
    });
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})
